#pragma once
#include "cinder/gl/TextureFont.h"
#include "cinder/app/AppBasic.h"
#include "cinder/ImageIo.h"

#include "Types.h"
#include "Renderer.h"
#include "rendering/SceneNode.h"
#include "ColliderBox.h"
#include "GameObject.h"
#include "Events.h"


using namespace Boon;
using namespace Rendering;

using namespace ci;
using namespace ci::app;



class DrawTextureNode : public Rendering::SceneNode
{
public:
	DrawTextureNode( GameObject& go, const Bounds& b )
		:	SceneNode( go.GetUniqueObjectID(), "draw_texture_node", Rendering::PASS_GAMEOBECT ),
		m_Bounds( b )
	{

	}

	virtual bool IsVisible( Scene* scene ) const
	{
		if( m_Pic )
			return true;
		else if( Get()->GetMaterial().GetImagePath().size() > 0 )
		{
			Surface bla( loadImage( Get()->GetMaterial().GetImagePath().c_str() ) );

			m_Pic = gl::Texture( bla );
			// default area drawing whole image
			m_AreaDrawing = ci::Area( 0, 0, m_Pic.getWidth(), m_Pic.getHeight());
			m_Pic.setFlipped();
		}
		return false;
	}

	virtual bool PreRender( Scene* scene ) 
	{
		gl::pushMatrices();
		Transform& t = Get()->GameObject().Lock()->GetTransform();
		Vector3 pos = t.GetPosition();
		gl::translate( pos.x, pos.y, pos.z );
		gl::rotate( Vec3f( 0, 0, t.GetRotation().GetAngle() ) );
		return true;
	}

	virtual bool Render( Scene* scene ) 
	{
		gl::draw(	m_Pic,
					m_AreaDrawing,
					Rectf( m_Bounds.boundMin.x, m_Bounds.boundMin.y, m_Bounds.boundMax.x, m_Bounds.boundMax.y ) );
		return true;
	}

	virtual bool PostRender( Scene* scene ) 
	{
		gl::popMatrices();
		return true;
	}
	void SetArea( uint_32 x, uint_32 y, uint_32 width, uint_32 height )
	{
		m_AreaDrawing.set( x, y, x + width, y + height );
	}

protected:
	mutable Area				m_AreaDrawing;
	
private:
	mutable ci::gl::Texture		m_Pic;
	const Bounds&				m_Bounds;

};




class DrawTexture : public Boon::Renderer
{
	GAMECOMPONENT( DrawTexture, Renderer )

	virtual IMessengerEventStrong GetEventCreateSceneNode() 
	{
		m_RenderPass = PASS_GAMEOBECT;
		m_Node = Shared_ptr<DrawTextureNode>( new DrawTextureNode( GetGameObject(), GetMaterial().GetBounds() ) );
		return IMessengerEventStrong( new Event_RenderComp_Created( *this, m_Node ) );
	}
protected:
	Shared_ptr<DrawTextureNode>			m_Node;

};

